<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <Header></Header>
      <div v-if="list.length">
        <List :list="list"></List>
      <Footer :list="list" 
      :allChackHandle="allChackHandle"
      :clearDoneHandle='clearDoneHandle'
      ></Footer>
      </div>
       <h1 v-else class="nolist">漂亮！任务都完成了哦！休息一下吧！</h1>
    </div>
  </div>
</template>

<script>
import PubSub from "pubsub-js";
import Header from "./components/Header.vue";
import List from "./components/List.vue";
import Footer from "./components/Footer.vue";

export default {
  mounted() {
    PubSub.subscribe("add", (msg, todoName) => {
      this.list.push({
        id: Date.now(),
        isDone: false,
        todoName,
      });
    });

    PubSub.subscribe('del',(msg,id)=>{
      this.list=this.list.filter((todo)=>todo.id!==id)

    });

    PubSub.subscribe('change',(msg,id)=>{
      console.log('接收change');

      this.list= this.list.map((todo)=>{
        if (todo.id === id) {
          todo.isDone = !todo.isDone;
        }
        return{...todo}
    })
    })
  },
  data() {
    return {
      // list: [
      //   {
      //     id: 1,
      //     isDone: true,
      //     todoName: "吃饭",
      //   },
      //   {
      //     id: 2,
      //     isDone: false,
      //     todoName: "睡觉",
      //   },
      // ],
      list:JSON.parse(localStorage.getItem('key'))||[]
    };
  },
  updated(){
    console.log('视图更新了');
    localStorage.setItem('key',JSON.stringify(this.list))
    // console.log(this.list);
  },
  methods: {
    // 点击全选改变状态
    allChackHandle() {
      // 判断是都全部选中
      console.log(111);
      const way = this.list.every((todo) => todo.isDone);

      // 直接修改原数据
      // this.list.forEach((todo) => (todo.isDone = !way));

      this.list= this.list.map((item) => {
        item.isDone =!way;
        return { ...item };
      });
    },
    clearDoneHandle(){
      console.log(111);
      this.list= this.list.filter((todo) => (!todo.isDone));
    }
  },
  components: {
    Header,
    List,
    Footer,
  },
};
</script>

<style>
/*base*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
    0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
.nolist{
  color: #bd362f;
  text-align: center;
}
</style>